

package com.easyseata.config.core;

import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.easyseata.common.ConfigurationKeys;
import com.easyseata.common.exception.NotSupportYetException;
import com.easyseata.common.load.EnhancedServiceLoader;
import com.easyseata.common.load.EnhancedServiceNotFoundException;
import com.easyseata.common.util.StringUtils;
import com.easyseata.config.file.FileConfiguration;

/**
 * The type Configuration factory.
 *
 */
public final class ConfigurationFactory {
	
	
	

    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationFactory.class);

    private static final String REGISTRY_CONF_DEFAULT = "registry";
    private static final String ENV_SYSTEM_KEY = "SEATA_ENV";
    public static final String ENV_PROPERTY_KEY = "seataEnv";

    private static final String SYSTEM_PROPERTY_SEATA_CONFIG_NAME = "seata.config.name";

    private static final String ENV_SEATA_CONFIG_NAME = "SEATA_CONFIG_NAME";

    public static volatile Configuration CURRENT_FILE_INSTANCE;

    public static volatile FileConfiguration ORIGIN_FILE_INSTANCE_REGISTRY;

    public static volatile FileConfiguration ORIGIN_FILE_INSTANCE = null;

    static {
        initOriginConfiguraction();
        load();
        maybeNeedOriginFileInstance();
    }

    private static void load() {
        Configuration configuration = ORIGIN_FILE_INSTANCE_REGISTRY;
        Configuration extConfiguration = null;
        try {
            extConfiguration = EnhancedServiceLoader.load(ExtConfigurationProvider.class).provide(configuration);
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("load Configuration from :{}",
                    extConfiguration == null ? configuration.getClass().getSimpleName() : "Spring Configuration");
            }
        } catch (EnhancedServiceNotFoundException e) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("failed to load extConfiguration: {}", e.getMessage(), e);
            }
        } catch (Exception e) {
            LOGGER.error("failed to load extConfiguration: {}", e.getMessage(), e);
        }
        CURRENT_FILE_INSTANCE = extConfiguration == null ? configuration : extConfiguration;
    }

    private static void initOriginConfiguraction() {
        String seataConfigName = System.getProperty(SYSTEM_PROPERTY_SEATA_CONFIG_NAME);
        if (seataConfigName == null) {
            seataConfigName = System.getenv(ENV_SEATA_CONFIG_NAME);
        }
        if (seataConfigName == null) {
            seataConfigName = REGISTRY_CONF_DEFAULT;
        }
        String envValue = System.getProperty(ENV_PROPERTY_KEY);
        if (envValue == null) {
            envValue = System.getenv(ENV_SYSTEM_KEY);
        }
        seataConfigName = envValue == null ? seataConfigName : seataConfigName + "-" + envValue;
        // create FileConfiguration for read registry.conf
        ORIGIN_FILE_INSTANCE_REGISTRY = new FileConfiguration(seataConfigName, false);
    }

    public static FileConfiguration getOriginFileInstanceRegistry() {
        return ORIGIN_FILE_INSTANCE_REGISTRY;
    }

    private static final String NAME_KEY = "name";
    private static final String FILE_TYPE = "file";

    private static volatile Configuration instance = null;

    /**
     * Gets instance.
     *
     * @return the instance
     */
    public static Configuration getInstance() {
        if (instance == null) {
            synchronized (Configuration.class) {
                if (instance == null) {
                    instance = buildConfiguration();
                }
            }
        }
        return instance;
    }

    private static void maybeNeedOriginFileInstance() {
        if (ConfigType.File.name().equalsIgnoreCase(getConfigType())) {
            String pathDataId = String.join(ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR,
                    ConfigurationKeys.FILE_ROOT_CONFIG, FILE_TYPE, NAME_KEY);
            String name = CURRENT_FILE_INSTANCE.getConfig(pathDataId);
            // create FileConfiguration for read file.conf
            ORIGIN_FILE_INSTANCE = new FileConfiguration(name);
        }
    }

    /**
     * Notes: should not rely on the ConfigType type, as it will prevent the extension of configuration types
     * implemented externally.
     * @return
     */
    private static String getConfigType() {
        String configTypeName = CURRENT_FILE_INSTANCE.getConfig(ConfigurationKeys.FILE_ROOT_CONFIG
            + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR + ConfigurationKeys.FILE_ROOT_TYPE);
        if (StringUtils.isBlank(configTypeName)) {
            throw new NotSupportYetException("config type can not be null");
        }
        return configTypeName;
    }

    public static Optional<FileConfiguration> getOriginFileInstance() {
        return Optional.ofNullable(ORIGIN_FILE_INSTANCE);
    }

    private static Configuration buildConfiguration() {
        String configTypeName = getConfigType();
        Configuration configuration = ORIGIN_FILE_INSTANCE;
        Configuration extConfiguration = getSpringConfiguration();
        try {
            Configuration configurationCache;
            if (null != extConfiguration) {
                configurationCache = ConfigurationCache.getInstance().proxy(extConfiguration);
            } else {
                configurationCache = ConfigurationCache.getInstance().proxy(configuration);
            }
            if (null != configurationCache) {
                extConfiguration = configurationCache;
            }
        } catch (Exception e) {
            LOGGER.error("failed to load configurationCacheProvider:{}", e.getMessage(), e);
        }
        return null == extConfiguration ? configuration : extConfiguration;
    }

    private static Configuration getSpringConfiguration() {
        Configuration configuration = ORIGIN_FILE_INSTANCE;
        if (null != configuration) {
            try {
                Configuration extConfiguration = EnhancedServiceLoader.load(ExtConfigurationProvider.class, false).provide(
                    configuration);
                if (null != extConfiguration) {
                    return extConfiguration;
                }
            } catch (EnhancedServiceNotFoundException ignore) {
                //ignore

            } catch (Exception exx) {
                LOGGER.error("failed to load spring configuration :{}", exx.getMessage(), exx);
            }
        }
        return null;
    }
    


    public static void reload() {
        ConfigurationCache.clear();
        initOriginConfiguraction();
        load();
        maybeNeedOriginFileInstance();
        instance = null;
        getInstance();
    }



}
